package api

import (
	"encoding/json"
	"fmt"

	"github.com/hyperledger/fabric/core/chaincode/shim"
	pb "github.com/hyperledger/fabric/protos/peer"

	"chaincode/model"
	"chaincode/pkg/utils"
)

func AddBadRecord(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	//验证参数
	if len(args) != 4 {
		return shim.Error("参数个数不满足！")
	}
	name := args[0]
	idCard := args[1]
	isLock := args[2]
	addTime := args[3]
	if name == "" || idCard == "" || isLock == "" || addTime == "" {
		return shim.Error("参数不可以为空！")
	}
	badRecord := model.BadRecord{
		Name:    name,
		IdCard:  idCard,
		IsLock:  isLock,
		AddTime: addTime,
	}
	//写入账本
	err := utils.WriteLedger(badRecord, stub, model.AddBadRecord, []string{badRecord.Name, badRecord.IdCard, badRecord.IsLock, badRecord.AddTime})
	if err != nil {
		return shim.Error(fmt.Sprintf("写入账本失败：%s", err.Error()))
	}
	badRecordByte, err := json.Marshal(badRecord)
	if err != nil {
		return shim.Error("反序列化失败！")
	}
	return shim.Success(badRecordByte)
}

// QueryBadRecord 查询不良记录
func SearchBadRecord(stub shim.ChaincodeStubInterface, args []string) pb.Response {
	var badRecordList []model.BadRecord
	results, err := utils.GetStateByPartialCompositeKeys2(stub, model.AddBadRecord, args)
	if err != nil {
		return shim.Error(fmt.Sprintf("%s", err))
	}
	for _, v := range results {
		if v != nil {
			var badRecord model.BadRecord
			err := json.Unmarshal(v, &badRecord)
			if err != nil {
				return shim.Error(fmt.Sprintf("QueryBadRecordlist-反序列化出错: %s", err))
			}
			badRecordList = append(badRecordList, badRecord)
		}
	}
	badRecordListByte, err := json.Marshal(badRecordList)
	if err != nil {
		return shim.Error(fmt.Sprintf("QueryBadRecord-序列化出错: %s", err))
	}
	return shim.Success(badRecordListByte)
}
